using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.FileProviders;
using System.IO;
using System.Threading.Tasks;
using System.Text;
using System.Text.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using MySqlConnector;
using System.Net.Http;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using System.Text.Encodings.Web;
using System.Globalization;
using System.Text.RegularExpressions;
using FinDataAdmin.Services;

// 注册编码提供程序
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);

var builder = WebApplication.CreateBuilder(args);

// 添加服务到容器
builder.Services.AddControllersWithViews();

// 添加会话服务
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromHours(2);
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
    options.Cookie.SameSite = SameSiteMode.Lax;
    options.Cookie.SecurePolicy = CookieSecurePolicy.None;
});

// 添加数据库服务
builder.Services.AddSingleton<DatabaseService>();

// 添加CORS服务
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowSpecificOrigins",
        builder => builder
            .WithOrigins("http://localhost:8001")
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials());
});

// 添加对DELETE等HTTP方法的支持
builder.Services.AddRouting(options => options.LowercaseUrls = true);

// 添加HttpClient服务
builder.Services.AddHttpClient();

var app = builder.Build();

// 获取数据库服务实例
var dbService = app.Services.GetRequiredService<DatabaseService>();

// 配置HTTP请求管道
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseExceptionHandler("/error");
    app.UseHsts();
}

// 使用CORS中间件
app.UseCors("AllowSpecificOrigins");

// 使用会话中间件
app.UseSession();

// 静态文件服务
app.UseStaticFiles();

// 添加对templates目录的访问
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(
        Path.Combine(Directory.GetCurrentDirectory(), "templates")),
    RequestPath = "/templates"
});

// 添加对static目录的访问
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(
        Path.Combine(Directory.GetCurrentDirectory(), "static")),
    RequestPath = "/static"
});

app.UseRouting();

// 初始化数据库
await dbService.InitializeDatabaseAsync();

// 初始化百度网盘链接数据
await InitializeBaiduPanLinksAsync(dbService);

// 添加终结点映射
app.UseEndpoints(endpoints =>
{
    // 管理员登录API
    endpoints.MapPost("/api/admin/login", async context =>
    {
        try
        {
            var dbService = context.RequestServices.GetRequiredService<DatabaseService>();
            
            // 获取表单数据
            var form = await context.Request.ReadFormAsync();
            string username = form["username"];
            string password = form["password"];

            Console.WriteLine($"管理员登录尝试 - 用户名: {username}");

            // 验证参数
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                Console.WriteLine("管理员登录失败 - 用户名或密码为空");
                context.Response.StatusCode = 400;
                await context.Response.WriteAsJsonAsync(new { detail = "用户名和密码不能为空" });
                return;
            }

            // 验证管理员
            var adminId = await dbService.ValidateAdminAsync(username, password);
            if (adminId > 0)
            {
                // 登录成功，设置会话
                context.Session.SetInt32("AdminId", adminId);
                context.Session.SetString("AdminUsername", username);
                
                Console.WriteLine($"管理员登录成功 - ID: {adminId}, 用户名: {username}");
                Console.WriteLine($"会话信息已设置 - AdminId: {context.Session.GetInt32("AdminId")}, AdminUsername: {context.Session.GetString("AdminUsername")}");
                
                await context.Response.WriteAsJsonAsync(new { success = true, message = "登录成功" });
            }
            else
            {
                Console.WriteLine("管理员登录失败 - 用户名或密码错误");
                context.Response.StatusCode = 401;
                await context.Response.WriteAsJsonAsync(new { detail = "用户名或密码错误" });
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"登录API异常: {ex.Message}");
            context.Response.StatusCode = 500;
            await context.Response.WriteAsJsonAsync(new { detail = "服务器内部错误，请稍后再试" });
        }
    });

    // 监管者API - 创建管理员
    endpoints.MapPost("/api/supervisor/create-admin", async context =>
    {
        try
        {
            // 检查监管者是否已登录
            string? supervisorToken = context.Session.GetString("SupervisorToken");
            if (string.IsNullOrEmpty(supervisorToken))
            {
                context.Response.StatusCode = 401;
                await context.Response.WriteAsJsonAsync(new { detail = "未登录或会话已过期" });
                return;
            }
            
            // 获取配置中的访问密钥
            var config = context.RequestServices.GetRequiredService<IConfiguration>();
            string validAccessKey = config["SupervisorCredentials:AccessKey"];
            
            // 验证访问密钥
            if (supervisorToken != validAccessKey)
            {
                context.Response.StatusCode = 403;
                await context.Response.WriteAsJsonAsync(new { detail = "无权访问" });
                return;
            }

            var dbService = context.RequestServices.GetRequiredService<DatabaseService>();
            
            // 获取表单数据
            var form = await context.Request.ReadFormAsync();
            string username = form["username"];
            string password = form["password"];

            // 验证参数
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsJsonAsync(new { detail = "用户名和密码不能为空" });
                return;
            }

            // 创建管理员
            bool success = await dbService.CreateAdminAsync(username, password);
            if (success)
            {
                await context.Response.WriteAsJsonAsync(new { success = true, message = "管理员创建成功" });
            }
            else
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsJsonAsync(new { detail = "管理员创建失败，可能用户名已存在" });
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"创建管理员API异常: {ex.Message}");
            context.Response.StatusCode = 500;
            await context.Response.WriteAsJsonAsync(new { detail = "服务器内部错误，请稍后再试" });
        }
    });

    // 监管者API - 删除管理员
    endpoints.MapDelete("/api/supervisor/delete-admin/{id}", async context =>
    {
        try
        {
            // 检查监管者是否已登录
            string? supervisorToken = context.Session.GetString("SupervisorToken");
            if (string.IsNullOrEmpty(supervisorToken))
            {
                context.Response.StatusCode = 401;
                await context.Response.WriteAsJsonAsync(new { detail = "未登录或会话已过期" });
                return;
            }
            
            // 获取配置中的访问密钥
            var config = context.RequestServices.GetRequiredService<IConfiguration>();
            string validAccessKey = config["SupervisorCredentials:AccessKey"];
            
            // 验证访问密钥
            if (supervisorToken != validAccessKey)
            {
                context.Response.StatusCode = 403;
                await context.Response.WriteAsJsonAsync(new { detail = "无权访问" });
                return;
            }

            var dbService = context.RequestServices.GetRequiredService<DatabaseService>();
            
            // 获取路由参数
            var id = context.Request.RouteValues["id"]?.ToString();
            if (string.IsNullOrEmpty(id) || !int.TryParse(id, out int adminId))
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsJsonAsync(new { detail = "无效的管理员ID" });
                return;
            }

            // 删除管理员
            bool success = await dbService.DeleteAdminAsync(adminId);
            if (success)
            {
                await context.Response.WriteAsJsonAsync(new { success = true, message = "管理员删除成功" });
            }
            else
            {
                context.Response.StatusCode = 404;
                await context.Response.WriteAsJsonAsync(new { detail = "管理员不存在或删除失败" });
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"删除管理员API异常: {ex.Message}");
            context.Response.StatusCode = 500;
            await context.Response.WriteAsJsonAsync(new { detail = "服务器内部错误，请稍后再试" });
        }
    });

    // 监管者API - 获取所有管理员
    endpoints.MapGet("/api/supervisor/admins", async context =>
    {
        try
        {
            // 检查监管者是否已登录
            string? supervisorToken = context.Session.GetString("SupervisorToken");
            if (string.IsNullOrEmpty(supervisorToken))
            {
                context.Response.StatusCode = 401;
                await context.Response.WriteAsJsonAsync(new { detail = "未登录或会话已过期" });
                return;
            }
            
            // 获取配置中的访问密钥
            var config = context.RequestServices.GetRequiredService<IConfiguration>();
            string validAccessKey = config["SupervisorCredentials:AccessKey"];
            
            // 验证访问密钥
            if (supervisorToken != validAccessKey)
            {
                context.Response.StatusCode = 403;
                await context.Response.WriteAsJsonAsync(new { detail = "无权访问" });
                return;
            }

            var dbService = context.RequestServices.GetRequiredService<DatabaseService>();
            
            // 获取所有管理员
            var admins = await dbService.GetAllAdminsAsync();
            await context.Response.WriteAsJsonAsync(admins);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"获取管理员列表API异常: {ex.Message}");
            context.Response.StatusCode = 500;
            await context.Response.WriteAsJsonAsync(new { detail = "服务器内部错误，请稍后再试" });
        }
    });

    // 首页路由
    endpoints.MapGet("/", async context =>
    {
        context.Response.Redirect("/admin/login");
    });

    // 管理员登录页面
    endpoints.MapGet("/admin/login", async context =>
    {
        await context.Response.WriteAsync(File.ReadAllText("templates/admin-login.html"));
    });

    // 监管者登录页面
    endpoints.MapGet("/supervisor/login", async context =>
    {
        await context.Response.WriteAsync(File.ReadAllText("templates/supervisor-login.html"));
    });
    
    // 监管者仪表盘页面
    endpoints.MapGet("/supervisor/dashboard", async context =>
    {
        // 检查监管者是否已登录
        string? supervisorToken = context.Session.GetString("SupervisorToken");
        if (string.IsNullOrEmpty(supervisorToken))
        {
            context.Response.Redirect("/supervisor/login");
            return;
        }

        await context.Response.WriteAsync(File.ReadAllText("templates/supervisor-dashboard.html"));
    });
    
    // 监管者登录API
    endpoints.MapPost("/api/supervisor/login", async context =>
    {
        try
        {
            // 获取表单数据
            var form = await context.Request.ReadFormAsync();
            string username = form["username"];
            string password = form["password"];

            // 输出调试信息
            Console.WriteLine($"监管者登录尝试 - 用户名: {username}");

            // 验证参数
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsJsonAsync(new { detail = "用户名和密码不能为空" });
                return;
            }

            // 获取配置
            var config = context.RequestServices.GetRequiredService<IConfiguration>();
            string usernameHash = config["SupervisorCredentials:UsernameHash"];
            string passwordHash = config["SupervisorCredentials:PasswordHash"];
            
            // 计算输入的哈希值
            string inputUsernameHash = ComputeSHA256Hash(username);
            string inputPasswordHash = ComputeSHA256Hash(password);
            
            Console.WriteLine($"监管者登录 - 用户名哈希验证: 输入={inputUsernameHash}");
            Console.WriteLine($"监管者登录 - 存储的用户名哈希: 配置={usernameHash}");
            Console.WriteLine($"监管者登录 - 哈希比较结果: 用户名匹配={inputUsernameHash == usernameHash}, 密码匹配={inputPasswordHash == passwordHash}");
            
            // 验证凭据
            if (inputUsernameHash == usernameHash && inputPasswordHash == passwordHash)
            {
                Console.WriteLine("监管者凭据验证成功（使用哈希）");
                // 登录成功，设置会话
                string accessKey = config["SupervisorCredentials:AccessKey"];
                context.Session.SetString("SupervisorToken", accessKey);
                context.Session.SetString("SupervisorUsername", username);
                
                await context.Response.WriteAsJsonAsync(new { success = true, message = "登录成功" });
            }
            else
            {
                // 为了方便调试，我们也允许使用明文凭据 tjumis/1895
                if (username == "tjumis" && password == "1895")
                {
                    Console.WriteLine("监管者凭据验证成功（使用明文）");
                    // 登录成功，设置会话
                    string accessKey = config["SupervisorCredentials:AccessKey"];
                    context.Session.SetString("SupervisorToken", accessKey);
                    context.Session.SetString("SupervisorUsername", username);
                    
                    await context.Response.WriteAsJsonAsync(new { success = true, message = "登录成功" });
                }
                else
                {
                    Console.WriteLine("监管者凭据验证失败");
                    context.Response.StatusCode = 401;
                    await context.Response.WriteAsJsonAsync(new { detail = "用户名或密码错误" });
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"监管者登录API异常: {ex.Message}");
            context.Response.StatusCode = 500;
            await context.Response.WriteAsJsonAsync(new { detail = "服务器内部错误，请稍后再试" });
        }
    });

    // 管理员主页
    endpoints.MapGet("/admin/dashboard", async context =>
    {
        // 检查管理员是否已登录
        int? adminId = context.Session.GetInt32("AdminId");
        if (adminId == null)
        {
            context.Response.Redirect("/admin/login");
            return;
        }

        await context.Response.WriteAsync(File.ReadAllText("templates/admin-dashboard.html"));
    });

    // 管理员API - 获取系统统计信息
    endpoints.MapGet("/api/admin/stats", async context =>
    {
        try
        {
            // 检查管理员是否已登录
            int? adminId = context.Session.GetInt32("AdminId");
            if (adminId == null)
            {
                context.Response.StatusCode = 401;
                await context.Response.WriteAsJsonAsync(new { detail = "未登录或会话已过期" });
                return;
            }

            var dbService = context.RequestServices.GetRequiredService<DatabaseService>();
            var stats = await dbService.GetSystemStatsAsync();
            
            await context.Response.WriteAsJsonAsync(stats);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"获取统计信息API异常: {ex.Message}");
            context.Response.StatusCode = 500;
            await context.Response.WriteAsJsonAsync(new { detail = "服务器内部错误，请稍后再试" });
        }
    });
    
    // 管理员API - 获取举报列表
    endpoints.MapGet("/api/admin/reports", async context =>
    {
        try
        {
            // 检查管理员是否已登录
            int? adminId = context.Session.GetInt32("AdminId");
            if (adminId == null)
            {
                context.Response.StatusCode = 401;
                await context.Response.WriteAsJsonAsync(new { detail = "未登录或会话已过期" });
                return;
            }

            var dbService = context.RequestServices.GetRequiredService<DatabaseService>();
            
            // 获取查询参数
            string status = context.Request.Query["status"].ToString() ?? "all";
            int.TryParse(context.Request.Query["page"].ToString(), out int page);
            int.TryParse(context.Request.Query["pageSize"].ToString(), out int pageSize);
            
            if (page <= 0) page = 1;
            if (pageSize <= 0) pageSize = 20;
            
            var reports = await dbService.GetReportsAsync(status, page, pageSize);
            await context.Response.WriteAsJsonAsync(reports);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"获取举报列表API异常: {ex.Message}");
            context.Response.StatusCode = 500;
            await context.Response.WriteAsJsonAsync(new { detail = "服务器内部错误，请稍后再试" });
        }
    });
    
    // 管理员API - 更新举报状态
    endpoints.MapPut("/api/admin/reports/{id}/status", async context =>
    {
        try
        {
            // 检查管理员是否已登录
            int? adminId = context.Session.GetInt32("AdminId");
            if (adminId == null)
            {
                context.Response.StatusCode = 401;
                await context.Response.WriteAsJsonAsync(new { detail = "未登录或会话已过期" });
                return;
            }

            // 获取路由参数
            if (!int.TryParse(context.Request.RouteValues["id"]?.ToString(), out int reportId))
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsJsonAsync(new { detail = "无效的举报ID" });
                return;
            }

            // 获取表单数据
            var form = await context.Request.ReadFormAsync();
            string status = form["status"];

            // 验证参数
            if (string.IsNullOrEmpty(status) || !new[] { "pending", "resolved", "rejected" }.Contains(status))
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsJsonAsync(new { detail = "无效的状态值，可选值为：pending, resolved, rejected" });
                return;
            }

            var dbService = context.RequestServices.GetRequiredService<DatabaseService>();
            bool success = await dbService.UpdateReportStatusAsync(reportId, status);
            
            if (success)
            {
                await context.Response.WriteAsJsonAsync(new { success = true, message = "举报状态已更新" });
            }
            else
            {
                context.Response.StatusCode = 404;
                await context.Response.WriteAsJsonAsync(new { detail = "举报不存在或更新失败" });
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"更新举报状态API异常: {ex.Message}");
            context.Response.StatusCode = 500;
            await context.Response.WriteAsJsonAsync(new { detail = "服务器内部错误，请稍后再试" });
        }
    });
    
    // 管理员API - 创建用户惩罚记录
    endpoints.MapPost("/api/admin/punishments", async context =>
    {
        try
        {
            // 检查管理员是否已登录
            int? adminId = context.Session.GetInt32("AdminId");
            if (adminId == null)
            {
                context.Response.StatusCode = 401;
                await context.Response.WriteAsJsonAsync(new { detail = "未登录或会话已过期" });
                return;
            }

            var form = await context.Request.ReadFormAsync();
            
            // 记录接收到的表单数据
            Console.WriteLine($"接收到处罚表单数据: userId={form["userId"]}, punishmentType={form["punishmentType"]}, " +
                $"durationDays={form["durationDays"]}, reason={form["reason"]}, reportId={form["reportId"]}, relatedReportId={form["relatedReportId"]}");
            
            // 验证必填字段
            if (!form.ContainsKey("userId") || !form.ContainsKey("punishmentType") || !form.ContainsKey("durationDays"))
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsJsonAsync(new { detail = "缺少必要的参数" });
                return;
            }

            // 解析参数
            if (!int.TryParse(form["userId"], out int userId))
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsJsonAsync(new { detail = "无效的用户ID" });
                return;
            }

            string punishmentType = form["punishmentType"];
            if (string.IsNullOrEmpty(punishmentType) || !new[] { "mute", "ban" }.Contains(punishmentType))
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsJsonAsync(new { detail = "无效的处罚类型，可选值为：mute, ban" });
                return;
            }

            if (!int.TryParse(form["durationDays"], out int durationDays) || durationDays <= 0)
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsJsonAsync(new { detail = "无效的处罚时长" });
                return;
            }

            string reason = form["reason"];
            
            // 支持两种参数名称：reportId或relatedReportId
            int? relatedReportId = null;
            if (!string.IsNullOrEmpty(form["relatedReportId"]) && int.TryParse(form["relatedReportId"], out int rid))
            {
                relatedReportId = rid;
            }
            else if (!string.IsNullOrEmpty(form["reportId"]) && int.TryParse(form["reportId"], out int rid2))
            {
                relatedReportId = rid2;
            }

            try
            {
                var dbService = context.RequestServices.GetRequiredService<DatabaseService>();
                int punishmentId = await dbService.CreateUserPunishmentAsync(userId, punishmentType, durationDays, reason, adminId.Value, relatedReportId);
                
                if (punishmentId > 0)
                {
                    Console.WriteLine($"成功创建处罚记录: ID={punishmentId}, 用户ID={userId}, 类型={punishmentType}");
                    await context.Response.WriteAsJsonAsync(new { success = true, message = "处罚已成功创建", punishmentId = punishmentId });
                }
                else
                {
                    Console.WriteLine($"创建处罚记录失败: 返回ID={punishmentId}");
                    context.Response.StatusCode = 400;
                    await context.Response.WriteAsJsonAsync(new { detail = "创建处罚记录失败" });
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"创建处罚记录数据库操作失败: {ex.Message}");
                throw;
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"创建处罚记录API异常: {ex.Message}");
            Console.WriteLine($"异常堆栈: {ex.StackTrace}");
            if (ex.InnerException != null)
            {
                Console.WriteLine($"内部异常: {ex.InnerException.Message}");
            }
            context.Response.StatusCode = 500;
            await context.Response.WriteAsJsonAsync(new { detail = "服务器内部错误，请稍后再试" });
        }
    });
    
    // 管理员API - 获取用户惩罚记录列表
    endpoints.MapGet("/api/admin/punishments", async context =>
    {
        try
        {
            // 检查管理员是否已登录
            int? adminId = context.Session.GetInt32("AdminId");
            if (adminId == null)
            {
                context.Response.StatusCode = 401;
                await context.Response.WriteAsJsonAsync(new { detail = "未登录或会话已过期" });
                return;
            }

            var dbService = context.RequestServices.GetRequiredService<DatabaseService>();
            
            // 获取查询参数
            int? userId = null;
            if (int.TryParse(context.Request.Query["userId"].ToString(), out int uid))
            {
                userId = uid;
            }
            
            int.TryParse(context.Request.Query["page"].ToString(), out int page);
            int.TryParse(context.Request.Query["pageSize"].ToString(), out int pageSize);
            
            if (page <= 0) page = 1;
            if (pageSize <= 0) pageSize = 20;
            
            var punishments = await dbService.GetUserPunishmentsAsync(userId, page, pageSize);
            await context.Response.WriteAsJsonAsync(punishments);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"获取用户惩罚记录API异常: {ex.Message}");
            context.Response.StatusCode = 500;
            await context.Response.WriteAsJsonAsync(new { detail = "服务器内部错误，请稍后再试" });
        }
    });
    
    // 管理员API - 解除用户处罚
    endpoints.MapDelete("/api/admin/punishments/{userId}", async context =>
    {
        try
        {
            // 检查管理员是否已登录
            int? adminId = context.Session.GetInt32("AdminId");
            if (adminId == null)
            {
                context.Response.StatusCode = 401;
                await context.Response.WriteAsJsonAsync(new { detail = "未登录或会话已过期" });
                return;
            }

            // 获取路由参数
            if (!int.TryParse(context.Request.RouteValues["userId"]?.ToString(), out int userId))
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsJsonAsync(new { detail = "无效的用户ID" });
                return;
            }

            var dbService = context.RequestServices.GetRequiredService<DatabaseService>();
            
            // 调用数据库服务解除用户处罚
            bool success = await dbService.RemoveUserPunishmentsAsync(userId);
            
            if (success)
            {
                Console.WriteLine($"成功解除用户ID={userId}的处罚");
                await context.Response.WriteAsJsonAsync(new { success = true, message = "已成功解除用户处罚" });
            }
            else
            {
                Console.WriteLine($"解除用户ID={userId}的处罚失败");
                context.Response.StatusCode = 404;
                await context.Response.WriteAsJsonAsync(new { detail = "找不到用户处罚记录或解除失败" });
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"解除用户处罚API异常: {ex.Message}");
            Console.WriteLine($"异常堆栈: {ex.StackTrace}");
            if (ex.InnerException != null)
            {
                Console.WriteLine($"内部异常: {ex.InnerException.Message}");
            }
            context.Response.StatusCode = 500;
            await context.Response.WriteAsJsonAsync(new { detail = "服务器内部错误，请稍后再试" });
        }
    });
    
    // 管理员API - 获取用户信息
    endpoints.MapGet("/api/admin/users/{id}", async context =>
    {
        try
        {
            // 检查管理员是否已登录
            int? adminId = context.Session.GetInt32("AdminId");
            if (adminId == null)
            {
                context.Response.StatusCode = 401;
                await context.Response.WriteAsJsonAsync(new { detail = "未登录或会话已过期" });
                return;
            }

            // 获取路由参数
            if (!int.TryParse(context.Request.RouteValues["id"]?.ToString(), out int userId))
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsJsonAsync(new { detail = "无效的用户ID" });
                return;
            }

            var dbService = context.RequestServices.GetRequiredService<DatabaseService>();
            var userInfo = await dbService.GetUserInfoAsync(userId);
            
            if (userInfo != null)
            {
                await context.Response.WriteAsJsonAsync(userInfo);
            }
            else
            {
                context.Response.StatusCode = 404;
                await context.Response.WriteAsJsonAsync(new { detail = "用户不存在" });
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"获取用户信息API异常: {ex.Message}");
            context.Response.StatusCode = 500;
            await context.Response.WriteAsJsonAsync(new { detail = "服务器内部错误，请稍后再试" });
        }
    });
    
    // 管理员API - 获取当前管理员信息
    endpoints.MapGet("/api/admin/info", async context =>
    {
        try
        {
            // 检查管理员是否已登录
            int? adminId = context.Session.GetInt32("AdminId");
            string? adminUsername = context.Session.GetString("AdminUsername");
            
            Console.WriteLine($"获取管理员信息API - 会话中的管理员ID: {adminId}, 用户名: {adminUsername}");
            
            if (adminId == null || string.IsNullOrEmpty(adminUsername))
            {
                Console.WriteLine("获取管理员信息API - 未登录或会话已过期");
                context.Response.StatusCode = 401;
                await context.Response.WriteAsJsonAsync(new { detail = "未登录或会话已过期" });
                return;
            }

            Console.WriteLine($"获取管理员信息API - 成功返回管理员信息: ID={adminId}, 用户名={adminUsername}");
            await context.Response.WriteAsJsonAsync(new { 
                id = adminId,
                username = adminUsername
            });
        }
        catch (Exception ex)
        {
            Console.WriteLine($"获取管理员信息API异常: {ex.Message}");
            context.Response.StatusCode = 500;
            await context.Response.WriteAsJsonAsync(new { detail = "服务器内部错误，请稍后再试" });
        }
    });
    
    // 管理员API - 获取用户列表
    endpoints.MapGet("/api/admin/users", async context =>
    {
        try
        {
            // 检查管理员是否已登录
            int? adminId = context.Session.GetInt32("AdminId");
            if (adminId == null)
            {
                context.Response.StatusCode = 401;
                await context.Response.WriteAsJsonAsync(new { detail = "未登录或会话已过期" });
                return;
            }

            var dbService = context.RequestServices.GetRequiredService<DatabaseService>();
            
            // 获取查询参数
            string searchTerm = context.Request.Query["search"].ToString() ?? "";
            int.TryParse(context.Request.Query["page"].ToString(), out int page);
            int.TryParse(context.Request.Query["pageSize"].ToString(), out int pageSize);
            
            if (page <= 0) page = 1;
            if (pageSize <= 0) pageSize = 20;
            
            var (users, totalCount) = await dbService.GetUsersAsync(page, pageSize, searchTerm);
            
            await context.Response.WriteAsJsonAsync(new {
                users = users,
                totalCount = totalCount,
                page = page,
                pageSize = pageSize,
                totalPages = (int)Math.Ceiling(totalCount / (double)pageSize)
            });
        }
        catch (Exception ex)
        {
            Console.WriteLine($"获取用户列表API异常: {ex.Message}");
            context.Response.StatusCode = 500;
            await context.Response.WriteAsJsonAsync(new { detail = "服务器内部错误，请稍后再试" });
        }
    });
    
    // 管理员API - 获取帖子列表
    endpoints.MapGet("/api/admin/posts", async context =>
    {
        try
        {
            // 检查管理员是否已登录
            int? adminId = context.Session.GetInt32("AdminId");
            if (adminId == null)
            {
                context.Response.StatusCode = 401;
                await context.Response.WriteAsJsonAsync(new { detail = "未登录或会话已过期" });
                return;
            }

            var dbService = context.RequestServices.GetRequiredService<DatabaseService>();
            
            // 获取查询参数
            string searchTerm = context.Request.Query["search"].ToString() ?? "";
            int.TryParse(context.Request.Query["page"].ToString(), out int page);
            int.TryParse(context.Request.Query["pageSize"].ToString(), out int pageSize);
            
            if (page <= 0) page = 1;
            if (pageSize <= 0) pageSize = 20;
            
            var (posts, totalCount) = await dbService.GetPostsAsync(page, pageSize, searchTerm);
            
            await context.Response.WriteAsJsonAsync(new {
                posts = posts,
                totalCount = totalCount,
                page = page,
                pageSize = pageSize,
                totalPages = (int)Math.Ceiling(totalCount / (double)pageSize)
            });
        }
        catch (Exception ex)
        {
            Console.WriteLine($"获取帖子列表API异常: {ex.Message}");
            context.Response.StatusCode = 500;
            await context.Response.WriteAsJsonAsync(new { detail = "服务器内部错误，请稍后再试" });
        }
    });
    
    // 管理员API - 获取帖子详情
    endpoints.MapPost("/api/admin/posts/{id}", async context =>
    {
        try
        {
            // 检查管理员是否已登录
            int? adminId = context.Session.GetInt32("AdminId");
            if (adminId == null)
            {
                context.Response.StatusCode = 401;
                await context.Response.WriteAsJsonAsync(new { detail = "未登录或会话已过期" });
                return;
            }

            // 获取路由参数
            if (!int.TryParse(context.Request.RouteValues["id"]?.ToString(), out int postId))
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsJsonAsync(new { detail = "无效的帖子ID" });
                return;
            }

            var dbService = context.RequestServices.GetRequiredService<DatabaseService>();
            var post = await dbService.GetPostByIdAsync(postId);
            
            if (post != null)
            {
                await context.Response.WriteAsJsonAsync(post);
            }
            else
            {
                context.Response.StatusCode = 404;
                await context.Response.WriteAsJsonAsync(new { detail = "帖子不存在" });
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"获取帖子详情API异常: {ex.Message}");
            context.Response.StatusCode = 500;
            await context.Response.WriteAsJsonAsync(new { detail = "服务器内部错误，请稍后再试" });
        }
    });

    // 管理员API - 获取百度网盘链接
    endpoints.MapGet("/api/admin/baidu-links", async context =>
    {
        try
        {
            // 检查管理员是否已登录
            int? adminId = context.Session.GetInt32("AdminId");
            if (adminId == null)
            {
                context.Response.StatusCode = 401;
                await context.Response.WriteAsJsonAsync(new { detail = "未登录或会话已过期" });
                return;
            }

            var dbService = context.RequestServices.GetRequiredService<DatabaseService>();
            var links = await dbService.GetAllBaiduPanLinksAsync();
            
            await context.Response.WriteAsJsonAsync(links);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"获取百度网盘链接API异常: {ex.Message}");
            context.Response.StatusCode = 500;
            await context.Response.WriteAsJsonAsync(new { detail = "服务器内部错误，请稍后再试" });
        }
    });
    
    // 管理员API - 获取特定类型的百度网盘链接
    endpoints.MapGet("/api/admin/baidu-links/{type}", async context =>
    {
        try
        {
            // 检查管理员是否已登录
            int? adminId = context.Session.GetInt32("AdminId");
            if (adminId == null)
            {
                context.Response.StatusCode = 401;
                await context.Response.WriteAsJsonAsync(new { detail = "未登录或会话已过期" });
                return;
            }

            // 获取路由参数
            string type = context.Request.RouteValues["type"]?.ToString();
            if (string.IsNullOrEmpty(type))
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsJsonAsync(new { detail = "链接类型不能为空" });
                return;
            }

            var dbService = context.RequestServices.GetRequiredService<DatabaseService>();
            var link = await dbService.GetBaiduPanLinkByTypeAsync(type);
            
            if (link != null)
            {
                await context.Response.WriteAsJsonAsync(link);
            }
            else
            {
                context.Response.StatusCode = 404;
                await context.Response.WriteAsJsonAsync(new { detail = "未找到指定类型的链接" });
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"获取百度网盘链接API异常: {ex.Message}");
            context.Response.StatusCode = 500;
            await context.Response.WriteAsJsonAsync(new { detail = "服务器内部错误，请稍后再试" });
        }
    });
    
    // 管理员API - 更新百度网盘链接
    endpoints.MapPost("/api/admin/baidu-links/update", async context =>
    {
        try
        {
            // 检查管理员是否已登录
            int? adminId = context.Session.GetInt32("AdminId");
            if (adminId == null)
            {
                context.Response.StatusCode = 401;
                await context.Response.WriteAsJsonAsync(new { detail = "未登录或会话已过期" });
                return;
            }

            var form = await context.Request.ReadFormAsync();
            string type = form["type"];
            string fileName = form["fileName"];
            string link = form["link"];
            string code = form["code"];

            // 验证参数
            if (string.IsNullOrEmpty(type) || string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(link) || string.IsNullOrEmpty(code))
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsJsonAsync(new { detail = "所有字段都不能为空" });
                return;
            }

            var dbService = context.RequestServices.GetRequiredService<DatabaseService>();
            bool success = await dbService.UpdateBaiduPanLinkAsync(type, fileName, link, code, adminId.Value);
            
            if (success)
            {
                await context.Response.WriteAsJsonAsync(new { success = true, message = $"{fileName} 链接已成功更新" });
            }
            else
            {
                context.Response.StatusCode = 500;
                await context.Response.WriteAsJsonAsync(new { detail = "更新链接失败" });
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"更新百度网盘链接API异常: {ex.Message}");
            context.Response.StatusCode = 500;
            await context.Response.WriteAsJsonAsync(new { detail = "服务器内部错误，请稍后再试" });
        }
    });
});

// 计算SHA256哈希值的辅助方法
static string ComputeSHA256Hash(string input)
{
    using (var sha256 = SHA256.Create())
    {
        var bytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(input));
        var builder = new StringBuilder();
        foreach (var b in bytes)
        {
            builder.Append(b.ToString("x2"));
        }
        return builder.ToString();
    }
}

// 初始化百度网盘链接数据
static async Task InitializeBaiduPanLinksAsync(DatabaseService dbService)
{
    try
    {
        Console.WriteLine("正在初始化百度网盘链接数据...");
        
        // 检查是否已存在数据
        var existingLinks = await dbService.GetAllBaiduPanLinksAsync();
        if (existingLinks != null && existingLinks.Count > 0)
        {
            Console.WriteLine($"已存在 {existingLinks.Count} 条百度网盘链接数据，跳过初始化");
            return;
        }
        
        // 初始化默认链接数据
        var defaultLinks = new List<(string type, string fileName, string link, string code)>
        {
            ("stock", "stock-trading-data.zip", "https://pan.baidu.com/s/1Cpm_rgIZ8fbi1W8RqQAaMw?pwd=h5ne", "h5ne"),
            ("index", "stock-main-index-data.zip", "https://pan.baidu.com/s/1I90UZIrkjgm7MfExkNtc1w?pwd=evax", "evax"),
            ("financial", "stock-fin-data-xbx.zip", "https://pan.baidu.com/s/1E92yN-Y60dPDp5mT-ap-1Q?pwd=bgpw", "bgpw")
        };
        
        // 获取默认管理员ID，如果没有则使用1
        int adminId = 1;
        
        // 添加默认链接
        foreach (var (type, fileName, link, code) in defaultLinks)
        {
            bool success = await dbService.UpdateBaiduPanLinkAsync(type, fileName, link, code, adminId);
            Console.WriteLine($"初始化 {type} 链接: {(success ? "成功" : "失败")}");
        }
        
        Console.WriteLine("百度网盘链接数据初始化完成");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"初始化百度网盘链接数据失败: {ex.Message}");
    }
}

// 启动应用
app.Run(); 